package com.example.administrator.uhf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.uhf.reader.CMD;
import com.example.administrator.uhf.reader.ERROR;
import com.example.administrator.uhf.reader.ReaderBase;
import com.example.administrator.uhf.reader.StringTool;
import com.example.administrator.uhf.reader.helper.OperateTagBuffer;
import com.example.administrator.uhf.reader.helper.ReaderHelper;
import com.example.administrator.uhf.reader.helper.ReaderSetting;
import com.example.administrator.uhf.reader.helper.OperateTagBuffer.OperateTagMap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WriteTag extends AppCompatActivity {
    private ReaderBase mReader;
    private Context mContext;
    private LocalBroadcastManager lbm;
    ListView Taglist,listView2;
    private  ArrayAdapter<CharSequence> Adapter1;
    List list1=new ArrayList();
Spinner  spinner;
TextView tv1;
EditText mDataEditText;
  private   String getlog;
    List as=new ArrayList();
Button btn2;
    ArrayAdapter<List>adapter;
  String az;
    private ReaderHelper mReaderHelper;
    private AccessListAdapter mAccessListAdapter;
    private List<OperateTagMap> data;
private  static ReaderSetting m_cur;
    private static OperateTagBuffer m_curO;
    private ArrayList<CharSequence> mLogListItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_tag);

        spinner=findViewById(R.id.spin01);
        tv1=findViewById(R.id.write_tag);
        mDataEditText=findViewById(R.id.tv);
        Taglist=findViewById(R.id.listview1);
        listView2=findViewById(R.id.listview2);
        btn2=findViewById(R.id.shuaxin);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             doublClick();
            }
        });
        lbm  = LocalBroadcastManager.getInstance(WriteTag.this);
        String arr[]=new String[]{"a","b","c","d","a","b","c","d","a","b","c","d","a","b","c","d","a","b","c","d"};
        list1.add("苹果");
        list1.add("香蕉");
        list1.add("草莓");
        adapter=new ArrayAdapter<List>(this,android.R.layout.simple_spinner_item,list1);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        ;
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener( new SpinnerSelect());
        spinner.setVisibility(View.VISIBLE);
        IntentFilter itent = new IntentFilter();
        itent.addAction(ReaderHelper.BROADCAST_WRITE_LOG);
        itent.addAction(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG);
        lbm.registerReceiver(mRecv, itent);
        data = new ArrayList<OperateTagMap>();

        mAccessListAdapter=new AccessListAdapter(WriteTag.this,data);
        Taglist.setAdapter(mAccessListAdapter );
        mLogListItem = new ArrayList<CharSequence>();
Adapter1=new ArrayAdapter(WriteTag.this,R.layout.tab_list,mLogListItem);
listView2.setAdapter(Adapter1);

        Log.e("data",""+data);

//        data.clear();
//
//        data.addAll(m_curO.lsTagList);


        try{
            mReaderHelper=ReaderHelper.getDefaultHelper();
            mReader=mReaderHelper.getReader();

        }catch (Exception e){
            e.printStackTrace();
        }

        m_cur = mReaderHelper.getCurReaderSetting();
        m_curO = mReaderHelper.getCurOperateTagBuffer();
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
write();


            }
        });



        Log.e("ls",""+m_curO.lsTagList);

    }


public  void  write(){
        byte btMemBank=0x01;
        byte bt2=0x00;
        byte []btAryPassWord={0,0,0,0};
        byte btWordAdd=0x02;
        byte btWordCnt=0x00;
        String [] result=null;
        byte[]btArrData=null;
           result = StringTool.stringToStringArray(mDataEditText.getText().toString().toUpperCase(), 2);  //数据
btArrData=StringTool.stringArrayToByteArray(result,result.length);
btWordCnt=(byte)((result.length/2+result.length%2)&0xFF);
        m_curO.clearBuffer();
        refres();
         mReader.writeTag(m_cur.btReadId,btAryPassWord,btMemBank,btWordAdd,btWordCnt,btArrData);








//        try {
//            btWordCnt = 0x04;
//
//        } catch (Exception e) {
//            Toast.makeText(WriteTag.this, "", Toast.LENGTH_SHORT).show();
//            return;
//        }
//    btWordCnt = 0x04;
//        m_curO.clearBuffer();
//        Log.e("", "123321");
//        refres();
//        mReader.readTag(m_cur.btReadId, bt2, btWordAdd, btWordCnt, btAryPassWord);


        Log.e("cpc", "");
    }



    public void read(){
        byte btWordCnt=0x00;
        byte bt2=0x00;
        byte btWordAdd=0x02;
        btWordCnt = 0x04;
        byte []btAryPassWord={0,0,0,0};
        m_curO.clearBuffer();
        Log.e("", "123321");
        refres();
        mReader.readTag(m_cur.btReadId, bt2, btWordAdd, btWordCnt, btAryPassWord);
    }


public  void refres(){
      data.clear();
      data.addAll(m_curO.lsTagList);
      Log.e("redata",""+data);

        mAccessListAdapter.notifyDataSetChanged();


}


    private final BroadcastReceiver mRecv = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ReaderHelper.BROADCAST_REFRESH_OPERATE_TAG)) {
                byte btCmd = intent.getByteExtra("cmd", (byte) 0x00);

                switch (btCmd) {

                    case CMD.READ_TAG:
                    case CMD.WRITE_TAG:
                    case CMD.LOCK_TAG:
                    case CMD.KILL_TAG:
                      refres();
                        break;
                }
            } else if (intent.getAction().equals(ReaderHelper.BROADCAST_WRITE_LOG)) {

writeLog(intent.getStringExtra("log"),intent.getIntExtra("type",ERROR.SUCCESS));
//                getlog=intent.getStringExtra("log");
//                Log.e("getlog",getlog);
            }
        }
    };


//    class  SpinnerSelect implements AdapterView.OnItemSelectedListener{
//
//
//        @Override
//        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//            Log.e("spinvalue",""+spinner.getSelectedItem());
//            az= (String) spinner.getSelectedItem();
//            Log.e("11111",""+az);
//            if (as.contains(az)){
//                tv1.setEnabled(false);
//                tv1.setBackgroundColor(getResources().getColor(R.color.gray));
//            }else {
//                tv1.setEnabled(true);
//                tv1.setBackgroundColor(getResources().getColor(R.color.blue));
//            }
//            az.isEmpty();
//        }
//
//        @Override
//        public void onNothingSelected(AdapterView<?> parent) {
//
//        }
//
//
//
//
//
//    }
public void writeLog(String strLog, int type) {
    Date now=new Date();
    SimpleDateFormat temp=new SimpleDateFormat("kk:mm:ss");
    SpannableString tSS = new SpannableString(temp.format(now) + ": " + strLog);
    tSS.setSpan(new ForegroundColorSpan(type == ERROR.SUCCESS ? Color.BLUE : Color.BLUE), 0, tSS.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  //��ɫ����
    mLogListItem.add(tSS);

    if (strLog.equals("写标签")){
        as.add(spinner.getSelectedItem());
        read();
        Log.e("tt","tta");
    }

    Log.e("tss",""+strLog);

    if (mLogListItem.size() > 50)
        mLogListItem.remove(0);

    Adapter1.notifyDataSetChanged();
}

    class  SpinnerSelect implements AdapterView.OnItemSelectedListener{


        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.e("spinvalue",""+spinner.getSelectedItem());
            az= (String) spinner.getSelectedItem();
            Log.e("11111",""+az);
            if (as.contains(az)){
                tv1.setEnabled(false);
                tv1.setBackgroundColor(getResources().getColor(R.color.gray));
            }else {
                tv1.setEnabled(true);
                tv1.setBackgroundColor(getResources().getColor(R.color.blue));
            }
            az.isEmpty();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }





    }

    private void doublClick(){
        mLogListItem.clear();
        Adapter1.notifyDataSetChanged();
    }

}
